package com.etoak.util;





import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * Java Bean 校验类
 */
public class ValidatorUtil {

    /** 校验器创建*/
    private static Validator validator;

    static {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
         validator= factory.getValidator();
    }

    public static void validate(Object object){
        //校验成功，集合为空
        Set<ConstraintViolation<Object>> violations =validator.validate(object);

        if(CollectionUtils.isNotEmpty(violations)){
            List<String> messageList = violations.stream().map(v->{
                //获得属性(name,email...)
                String filed = v.getPropertyPath().toString();
                //获得message的信息
                String message = v.getMessage();
                return StringUtils.join(filed,message);
            }).collect(Collectors.toList());

            throw new RuntimeException(StringUtils.join(messageList,";"));
        }
    }
}
